package com.avego.game;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Game
{
	private Board board;
	private Referee referee;
	private List<Player> mPlayers;

	public Game()
	{
		mPlayers = new ArrayList<Player>();
	}

	
	/**
	 * Add the players into a Threadpool and waits until a player is the winner.
	 *
	 * @throws InterruptedException the interrupted exception
	 */
	public void gameOn() throws InterruptedException
	{
		ExecutorService executor = Executors.newFixedThreadPool(mPlayers.size());

		Map<Future<Boolean>, Player> list = new HashMap<Future<Boolean>, Player>();

		for (Player player : mPlayers)
		{
			Thread.sleep(1000 / mPlayers.size());

			synchronized (board)
			{
				board.addPlayer(player);
			}

			Future<Boolean> submit = executor.submit(player);

			list.put(submit, player);
		}

		for (Future<Boolean> future : list.keySet())
		{
			try
			{
				boolean value = future.get();
				if (value)
				{
					int winner = list.get(future).getPlayerNumber();
					System.out.println("The Winner is Player " + winner);
				}
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			catch (ExecutionException e)
			{
				e.printStackTrace();
			}
		}
		executor.shutdown();

	}

	public Board getBoard()
	{
		return board;
	}

	public void setBoard(Board board)
	{
		this.board = board;
	}

	public Referee getReferee()
	{
		return referee;
	}

	public void setReferee(Referee referee)
	{
		this.referee = referee;
	}

	public void addPlayer(Player player)
	{
		mPlayers.add(player);
	}

}
